<template>
  <div class="project-detail-box detail-box">
    <div class="detail-title">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/panel/project/management' }">项目列表</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/panel/project/detail' }">项目详情</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button type="primary" plain size="small" @click="detailCancel">返回</el-button>
      <el-button type="primary" size="small" @click="detailSave">保存</el-button>
      <el-button v-if="pid" type="danger" plain size="small" @click="detailDelete">删除</el-button>
    </div>
    <el-form v-model="form" ref="form" class="detail-form">
      <el-form-item label="项目名称：">
        <el-input placeholder="请输入" size="small" v-model="form.pName"></el-input>
      </el-form-item>
      <el-form-item label="项目编号：">
        <el-input placeholder="请输入" size="small" v-model="form.pNumber"></el-input>
      </el-form-item>
      <el-form-item label="项目类型：">
        <el-select v-model="form.projType" filterable placeholder="请选择" size="small">
          <el-option
            v-for="item in form.projTypeOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!--<el-button type="primary" plain @click="addTypeD" size="small">添加项目类型</el-button>-->
      </el-form-item>
      <el-form-item label="项目负责人：">
        <el-select v-model="form.responseM" filterable placeholder="请选择" size="small">
          <el-option
            v-for="item in form.responseMOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经营联系人：">
        <el-select v-model="form.contactM" filterable placeholder="请选择" size="small">
          <el-option
            v-for="item in form.contactMOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与人员：">
        <el-select style="width: 100%" v-model="form.techP" multiple placeholder="请选择" size="small">
          <el-option
            v-for="item in form.techPOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="立项时间：">
        <el-date-picker
          v-model="form.startDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          size="small">
        </el-date-picker>
        <el-checkbox v-model="form.paperSigned">合同已签署</el-checkbox>
      </el-form-item>
      <el-row :gutter="20" class="col-input">
        <el-col :span="12">
          <el-form-item label="合同金额：">
            <el-input placeholder="请输入" v-model="form.paperA" size="small"></el-input>元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已到款金额：">
            <el-input placeholder="请输入" v-model="form.receivedA" size="small"></el-input>元
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="col-input">
        <el-col :span="12">
          <el-form-item label="部门产值：">
            <el-input placeholder="请输入" v-model="form.departmentP" size="small"></el-input>元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已结算产值：">
            <el-input placeholder="请输入" v-model="form.settledP" size="small"></el-input>元
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="项目状态：">
        <el-select v-model="form.projectState" placeholder="请选择" size="small">
          <el-option
            v-for="item in form.projectStateOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产值分配：">
        <el-checkbox v-model="form.finishDis">分配完成</el-checkbox>
      </el-form-item>
      <el-row :gutter="20" class="col-input" v-if="pid">
        <el-col :span="12">
          <el-form-item label="质检系数：">
            <el-input placeholder="" v-model="form.qcoe" size="small" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <div class="qcsp">
            <el-button type="warning" @click="dialogVisible = true" size="small">质检审批</el-button>
          </div>
        </el-col>
      </el-row>
      <el-form-item label="项目描述：">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 4}"
          placeholder="请输入内容"
          v-model="form.projectDescribe">
        </el-input>
      </el-form-item>
      <el-form-item label="项目任务单：">
        <el-upload
          class="upload-demo"
          action="http://47.96.125.181:8848/upload"
          :multiple="false"
          accept = "image/*"
          :http-request="uploadFile"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
          :on-preview = "handleOnPreview"
          :file-list="form.taskImgs">
          <el-button size="small" type="primary">点击上传</el-button>
          <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>-->
        </el-upload>
      </el-form-item>
      <el-form-item label="项目结算单：">
        <el-upload
          style="width: 100%"
          class="upload-demo"
          action="http://47.96.125.181:8848/upload"
          :multiple="false"
          accept = "image/*"
          :http-request="uploadFile2"
          :on-success="handleUploadSuccess2"
          :on-remove="handleRemove2"
          :on-preview = "handleOnPreview"
          :file-list="form.balanceImgs">
          <el-button size="small" type="primary">点击上传</el-button>
          <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>-->
        </el-upload>
      </el-form-item>
    </el-form>
    <el-dialog
      title="质检系数审批(审批通过后生效)"
      :visible.sync="dialogVisible"
      width="50%"
      class="filter-eddit-dialog">
      <el-form  ref="form" v-model="form">
        <el-form-item label="质检系数：">
          <div class="zjxs">
            <el-input placeholder="请输入质检系数" v-model="form.qcoeX" size="small"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="审批人：">
          <el-select v-model="form.qcM" clearable placeholder="请选择" size="mini">
            <el-option
              v-for="item in form.qcOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="warning" @click="qcApprove">提交审批</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data(){
      return{
        dialogVisible:false,
        pid:'',
        droplist:{},
        form:{
          finishDis:false,
          qcoeX:'',
          qcoe:0.0,
          pName:'',
          pNumber:'',
          projType:'',
          projTypeOptions:[],
          contactM:'',
          contactMOptions:[],
          responseM:'',
          responseMOptions:[],
          techP:[],
          techPOptions:[],
          qcM:'',
          qcOptions:[],
          projectState:'',
          projectStateOptions:[
            {value:0,label:'准备'},
            {value:1,label:'作业中'},
            {value:2,label:'作业完成'},
            {value:3,label:'归档'},
            {value:4,label:'结算'},
            {value:5,label:'结束'},

          ],
          startDate:'',
          paperSigned:false,
          paperA:'',
          receivedA:'',
          departmentP:'',
          settledP:'',
          projectDescribe:'',
          taskImgs: [],
          balanceImgs: []
        }
      }
    },
    created: function(){
      let user = JSON.parse(window.localStorage.getItem('access-user'))
      this.token = user.Token
      this.getDropList().then((flag) => {
        if (flag) {
          let pid = parseInt(this.$route.query.id)
          this.pid = pid
          if (!isNaN(pid)) {
            this.$http.post(this.domain + '/project/detail', {
              token: this.token,
              id: pid
            }).then((response) => {
              if (response.data.Success) {
//                console.log(response.data)
                this.form.pName = response.data.Project.ProjectName
                this.form.pNumber = response.data.Project.ProjectNumber
                this.form.projType = response.data.Project.ProjectType
                this.form.responseM = response.data.Project.PmId
                this.form.contactM = response.data.Project.OmId
                for (var index in response.data.Engineers) {
                  this.form.techP.push(response.data.Engineers[index].ID)
                }
                this.form.startDate = response.data.Project.CreatedDate
                this.form.paperSigned = response.data.Project.ContractSigned
                this.form.paperA = response.data.Project.ContractAmount
                this.form.receivedA = response.data.Project.ReceivedAmount
                this.form.departmentP = response.data.Project.DepartmentOutput
                this.form.settledP = response.data.Project.BalancedOutput
                this.form.projectState = response.data.Project.Status
                this.form.projectDescribe = response.data.Project.Desc
                this.form.qcoe = response.data.Project.Qcoe
                this.form.finishDis = response.data.Project.FinishDis

                for (var index in response.data.TaskImgs) {
                  var img = {
                    name:response.data.TaskImgs[index].ImgUrl.split('/').pop(),
                    url:response.data.TaskImgs[index].ImgUrl
                  }
                  this.form.taskImgs.push(img)
                }
                for (var index in response.data.BalanceImgs) {
                  var img = {
                    name:response.data.BalanceImgs[index].ImgUrl.split('/').pop(),
                    url:response.data.BalanceImgs[index].ImgUrl
                  }
                  this.form.balanceImgs.push(img)
                }

                this.$message.success(response.data.Msg)
              } else {
                this.$message.error(response.data.Msg)
              }
            }).catch(function (response) {
              this.$message.error(response.data)
            })
          } else {
//            console.log(pid)
          }
        }
      })
    },
    methods:{
      qcApprove(){
        let args = {
          token: this.token,
          projectid: this.pid,
          approveuser:this.form.qcM,
          qcoe:parseFloat(this.form.qcoeX)
        }
//        console.log(args)
        this.$http.post(this.domain + '/approve/submit',
          args
        ).then((response) => {
          if (response.data.Success) {
//            console.log(response.data)
            this.$message.success(response.data.Msg)
          } else {
            this.$message.error(response.data.Msg)
          }
          this.dialogVisible = false
        }).catch(function (response) {
          this.$message.error(response.data)
          this.dialogVisible = false
        })
      },
      handleOnPreview (file) {
//        console.log(file)
        window.open(file.url)
      },
      remove (arr,obj) {
        var index = 0
        var flag = false
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].url === obj) {
            index = i
            flag = true
            break
          }
        }
        if (flag) {
          arr.splice(index,1)
        }
      },
      uploadFile2 (content) {
        let formData = new FormData()
        formData.append('Image', content.file)
        this.$http.post(this.domain + '/upload', formData)
          .then((response) => {
            this.$message.success(response.data.Msg + "，项目保存后生效")
            content.onSuccess(response)
          })
      },
      handleUploadSuccess2 (response, file) {
        var img = {
          name:response.data.ImgUrl.split('/').pop(),
          url:response.data.ImgUrl
        }
        this.form.balanceImgs.push(img)
      },
      handleRemove2 (file) {
        this.remove(this.form.taskImgs,file.url)
        this.$message.success("删除成功，项目保存后生效")
      },
      uploadFile (content) {
        let formData = new FormData()
        formData.append('Image', content.file)
        this.$http.post(this.domain + '/upload', formData)
          .then((response) => {
            this.$message.success(response.data.Msg+ "，项目保存后生效")
            content.onSuccess(response)
          })
      },
      handleUploadSuccess (response, file) {
        var img = {
          name:response.data.ImgUrl.split('/').pop(),
          url:response.data.ImgUrl
        }
        this.form.taskImgs.push(img)
      },
      handleRemove (file) {
        this.remove(this.form.taskImgs,file.url)
        this.$message.success("删除成功，项目保存后生效")
      },
      handleClose(tag) {
        this.engineers.splice(this.engineers.indexOf(tag), 1);
      },
      getDropList () {
        return new Promise((resolve,reject) => {
          this.$http.post(this.domain + '/droplist', {
            token: this.token
          }).then((response) => {
            if (response.data.Success) {
//              console.log(response.data)
              this.droplist = response.data
              for (var index in this.droplist.ProjectTypes) {
                var temp = {
                  value:this.droplist.ProjectTypes[index].ProjectType,
                  label:this.droplist.ProjectTypes[index].TypeName
                }
                this.form.projTypeOptions.push(temp)
              }
              for (var index in this.droplist.Oms) {
                var temp = {
                  value:this.droplist.Oms[index].ID,
                  label:this.droplist.Oms[index].RealName
                }
                this.form.contactMOptions.push(temp)
              }
              for (var index in this.droplist.Pms) {
                var temp = {
                  value:this.droplist.Pms[index].ID,
                  label:this.droplist.Pms[index].RealName
                }
                this.form.responseMOptions.push(temp)
              }
              for (var index in this.droplist.Enginners) {
                var temp = {
                  value:this.droplist.Enginners[index].ID,
                  label:this.droplist.Enginners[index].RealName
                }
                this.form.techPOptions.push(temp)
              }
              for (var index in this.droplist.Qcs) {
                var temp = {
                  value:this.droplist.Qcs[index].ID,
                  label:this.droplist.Qcs[index].RealName
                }
                this.form.qcOptions.push(temp)
              }
//              console.log(this.form)
              resolve(response.data.Success)
            } else {
              this.$message.error(response.data.Msg)
              reject(response)
            }
          }).catch(function (response) {
            this.$message.error(response.data)
            reject(response)
          })
        })
      },
      detailCancel(){
        this.$router.go(-1)
      },
      detailDelete(){
        this.$confirm('确认删除该项目吗?', '提示', {
          confirmButtonClass: 'el-button--warning'
        }).then(() => {
          this.$http.post(this.domain + '/project/delete',
            {
              token:this.token,
              projectid:this.pid
            }
          ).then((response) => {
            if (response.data.Success) {
              this.$message.success(response.data.Msg)
              this.$router.go(-1)
            } else {
              this.$message.error(response.data.Msg)
            }
          }).catch((response) => {
            this.$message.error(response.data)
          })
        }).catch(() => {})
      },
      detailSave(){
        var args = {
          token: this.token,
          sgined:this.form.paperSigned,
          finish:this.form.finishDis,
          desc:this.form.projectDescribe
        }
        if (!isNaN(this.pid)) {
          args.projectid = this.pid
        }
        if (this.form.pName !== "") {
          args.projectname = this.form.pName
        } else {
          this.$message.error("请输入项目名称")
          return
        }
        if (this.form.pNumber !== "") {
          args.projectnumber = this.form.pNumber
        } else {
          this.$message.error("请输入项目编号")
          return
        }
        if (this.form.projType !== "") {
          args.projecttype = this.form.projType
        } else {
          this.$message.error("请选择项目类型")
          return
        }
        if (this.form.responseM !== "") {
          args.pmid = this.form.responseM
        } else {
          this.$message.error("请选择项目负责人")
          return
        }
        // 运营联系人非必填
        if (this.form.contactM !== "") {
          args.omid = this.form.contactM
        } else {
          args.omid = 0
        }
        if (this.form.startDate !== "") {
          args.createdate = this.form.startDate
          if (this.form.startDate.length === 10) {
            args.createdate += " 00:00:00"
          }
        } else {
          this.$message.error("请选择立项日期")
          return
        }
        if (this.form.projectState !== "") {
          args.status = this.form.projectState
        } else {
          this.$message.error("请选择项目状态")
          return
        }
        var engineers = ''
        for (var index in this.form.techP) {
          engineers += this.form.techP[index]+ ","
        }
        args.engineers = engineers
        var taskimgs = ''
        for (var index in this.form.taskImgs) {
          taskimgs += this.form.taskImgs[index].url+ ","
        }
        args.taskimgs = taskimgs

        var balanceimgs = ''
        for (var index in this.form.balanceImgs) {
          balanceimgs += this.form.balanceImgs[index].url+ ","
        }
        args.balanceimgs = balanceimgs

        var contractamount = parseFloat(this.form.paperA)
        if (!isNaN(contractamount)) {
          args.contractamount = contractamount
        }
        var receivedamount = parseFloat(this.form.receivedA)
        if (!isNaN(receivedamount)) {
          args.receivedamount = receivedamount
        }
        var departmentoutput = parseFloat(this.form.departmentP)
        if (!isNaN(departmentoutput)) {
          args.departmentoutput = departmentoutput
        }
        var balancedoutput = parseFloat(this.form.settledP)
        if (!isNaN(balancedoutput)) {
          args.balancedoutput = balancedoutput
        }
//        console.log(args)
        this.$http.post(this.domain + '/project/edit',
          args
        ).then((response) => {
          if (response.data.Success) {
            this.$message.success(response.data.Msg)
            this.pid = response.data.Project.ID
          } else {
            this.$message.error(response.data.Msg)
          }
        }).catch(function (response) {
          this.$message.error(response.data)
        })
      },
      addTypeD() {
        this.$prompt('添加项目类型', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '请输入需添加项目类型'
        }).then(({ value }) => {
          this.$http.post(this.domain + '/project/addtype', {
            token: this.token,
            typename: value
          }).then((response) => {
            if (response.data.Success) {
//              console.log(response.data)
              var temp = {
                value:response.data.Data.ProjectType,
                label:response.data.Data.TypeName
              }
              this.form.projTypeOptions.push(temp)
              this.$message.success(response.data.Msg)
            } else {
              this.$message.error(response.data.Msg)
            }
          }).catch(function (response) {
            this.$message.error(response.data)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      }
    }
  }
</script>

<style>
  .zjxs{
    float: left;
  }
  .qcsp{
    margin-top: 4px;
  }
  .project-detail-box .detail-title{
    height: 32px;
    line-height: 32px;
    margin-bottom: 20px;
  }
  .detail-title h4{
    display: inline-block;
  }
  .detail-title button{
    float: right;
    /*margin-left: 15px;*/
  }
  .detail-title button:nth-of-type(1){
    margin-left: 10px;
  }

  .detail-form .el-form-item__label{
    width:100px;
  }
  .detail-form .el-form-item__content{
    width: calc(100% - 100px);
    display: inline-block;
  }
  .col-input .el-input{
    width: calc(100% - 40px);
    margin-right: 20px;
  }
  .project-detail-box .el-upload-list.el-upload-list--text{
    width: 200px;
  }
</style>
